<!-- 
 * @Author: zhuxiaoyi
 * @Date: 2024-01-09 10:50:36
 * @LastEditor: zhuxiaoyi
 * @LastEditTime: 2025-06-25 15:26:25
 * @Description: 测站数据折线图展示组件 - 支持多选数据类型和导出功能
-->
<template>
  <div class="station-data-chart" :style="{ height: view.height - 132 + 'px' }">
    <div class="layout-container" :style="{ height: view.height - 132 + 'px' }">
      <!-- 左侧查询条件 -->
      <div class="left-panel" :style="{ height: view.height - 132 + 'px' }">
        <el-card class="search-card" shadow="hover" :style="{ height: '100%' }">
          <template #header>
            <div class="card-header">
              <span>查询条件</span>
            </div>
          </template>

          <div
            class="form-container"
            :style="{ height: view.height - 320 + 'px' }"
          >
            <el-form
              :model="searchForm"
              label-width="100px"
              label-position="top"
            >
              <!-- 测站类型选择 -->
              <el-form-item label="测站类型" required>
                <el-radio-group
                  v-model="searchForm.stationTypeCode"
                  @change="handleStationTypeChange"
                >
                  <el-radio
                    v-for="item in stationTypeOptions"
                    :key="item.stationTypeCode"
                    :label="item.stationTypeCode"
                    border
                    style="width: 100%; margin-bottom: 8px"
                  >
                    {{ item.stationTypeName }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>

              <!-- 数据类型选择 - 支持多选 -->
              <el-form-item label="数据类型" v-if="searchForm.stationTypeCode">
                <el-select
                  v-model="searchForm.dataTypes"
                  @change="handleDataTypeChange"
                  placeholder="请选择数据类型（可多选）"
                  filterable
                  clearable
                  multiple
                  collapse-tags
                  collapse-tags-tooltip
                  :max-collapse-tags="3"
                  style="width: 100%"
                  :loading="dataTypeLoading"
                  no-data-text="暂无数据类型"
                  filter-method="filterDataType"
                >
                  <!-- 如果数据类型数量较少，直接显示 -->
                  <template v-if="dataTypeOptions.length <= 10">
                    <el-option
                      v-for="item in dataTypeOptions"
                      :key="item.dataTypeCode"
                      :label="item.dataTypeName || item.dataTypeCode"
                      :value="item.dataTypeCode"
                    >
                      <span style="float: left">{{ item.dataTypeName || item.dataTypeCode }}</span>
                      <span style="float: right; color: #8492a6; font-size: 13px">{{ item.dataTypeCode }}</span>
                    </el-option>
                  </template>
                  
                  <!-- 如果数据类型数量较多，分组显示 -->
                  <template v-else>
                    <el-option-group
                      v-for="group in groupedDataTypes"
                      :key="group.label"
                      :label="group.label"
                    >
                      <el-option
                        v-for="item in group.options"
                        :key="item.dataTypeCode"
                        :label="item.dataTypeName || item.dataTypeCode"
                        :value="item.dataTypeCode"
                      >
                        <span style="float: left">{{ item.dataTypeName || item.dataTypeCode }}</span>
                        <span style="float: right; color: #8492a6; font-size: 13px">{{ item.dataTypeCode }}</span>
                      </el-option>
                    </el-option-group>
                  </template>
                </el-select>
                <div v-if="searchForm.dataTypes.length > 0" class="selected-types-info">
                  已选择 {{ searchForm.dataTypes.length }} 个数据类型
                </div>
              </el-form-item>

              <!-- 测站选择 -->
              <el-form-item label="测站" v-if="searchForm.stationTypeCode">
                <el-select
                  v-model="searchForm.stationCode"
                  @change="handleStationChange"
                  placeholder="请选择测站"
                  filterable
                  clearable
                  style="width: 100%"
                  :loading="stationLoading"
                  no-data-text="暂无测站数据"
                >
                  <el-option
                    v-for="item in stationOptions"
                    :key="item.stcd"
                    :label="item.stnm || item.stcd"
                    :value="item.stcd"
                  >
                    <span style="float: left">{{
                      item.stnm || item.stcd
                    }}</span>
                    <span
                      style="float: right; color: #8492a6; font-size: 13px"
                      >{{ item.stcd }}</span
                    >
                  </el-option>
                </el-select>
              </el-form-item>

              <!-- 日期范围选择 -->
              <el-form-item label="日期范围" required>
                <el-date-picker
                  v-model="dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                  :shortcuts="dateShortcuts"
                />
              </el-form-item>

              <!-- 查询按钮 -->
              <el-form-item>
                <el-button
                  type="primary"
                  @click="handleSearch"
                  :disabled="!isSearchValid"
                  :loading="loading"
                  style="width: 100%; margin-bottom: 8px"
                >
                  <el-icon><Search /></el-icon>查询
                </el-button>
                <el-button @click="handleReset" style="width: 100%">
                  <el-icon><Refresh /></el-icon>重置
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
      </div>

      <!-- 右侧内容区域 -->
      <div class="right-panel" :style="{ height: view.height - 32 + 'px' }">
        <!-- 图表展示区域 -->
        <el-card
          class="chart-card"
          shadow="hover"
          v-loading="loading"
          :style="{ height: view.height - 732 + 'px' }"
        >
          <template #header>
            <div class="chart-header">
              <div class="chart-title" v-if="chartTitle">
                <h3>{{ chartTitle }}</h3>
              </div>
              <div class="chart-actions" v-if="hasData">
                <el-button
                  type="primary"
                  size="small"
                  @click="exportChart"
                  :loading="exportLoading"
                >
                  <el-icon><Download /></el-icon>导出图表
                </el-button>
              </div>
            </div>
          </template>

          <div
            id="lineChart"
            class="chart-container"
            :style="{ height: view.height - 992 + 'px' }"
          ></div>

          <!-- 无数据提示 -->
          <el-empty
            v-if="!hasData && !loading"
            description="暂无数据"
          ></el-empty>
        </el-card>

        <!-- 数据表格展示 -->
        <el-card
          class="table-card"
          shadow="hover"
          v-if="hasData"
          :style="{ height: (view.height - 32) * 0.5 + 'px' }"
        >
          <template #header>
            <div class="table-header">
              <div class="table-info">
                <span class="title">数据详情</span>
                <span class="data-count">共 {{ pagination.total }} 条数据</span>
              </div>
              <div class="table-actions">
                <el-dropdown @command="handleExportData" trigger="click">
                  <el-button type="primary" size="small" :loading="exportLoading">
                    <el-icon><Download /></el-icon>导出数据
                    <el-icon><ArrowDown /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="excel">导出为 Excel</el-dropdown-item>
                      <el-dropdown-item command="csv">导出为 CSV</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
          </template>

          <div
            class="table-container"
            :style="{ height: (view.height - 32) * 0.4 - 130 + 'px' }"
          >
            <el-table
              :data="tableData"
              stripe
              border
              :height="(view.height - 132) * 0.4"
              style="width: 100%"
              size="small"
            >
              <el-table-column
                prop="stationCode"
                label="测站编码"
                width="120"
                fixed
              ></el-table-column>
              <el-table-column
                prop="stationName"
                label="测站名称"
              ></el-table-column>
              <el-table-column
                prop="stationTypeCode"
                label="测站类型编码"
              ></el-table-column>
              <el-table-column
                prop="stationTypeName"
                label="测站类型名称"
              ></el-table-column>
              <el-table-column
                prop="dataType"
                label="数据类型编码"
              ></el-table-column>
              <el-table-column
                prop="dataTypeName"
                label="数据类型名称"
              ></el-table-column>
              <el-table-column prop="monitoringDate" label="监测时间">
                <template #default="scope">
                  {{ formatDate(scope.row.monitoringDate) }}
                </template>
              </el-table-column>
              <el-table-column
                prop="monitoringValue"
                label="监测值"
                width="120"
              >
                <template #default="scope">
                  {{ formatValue(scope.row.monitoringValue) }}
                </template>
              </el-table-column>
            </el-table>
          </div>

          <div class="pagination-container">
            <el-pagination
              v-model:current-page="pagination.pageNum"
              v-model:page-size="pagination.pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="pagination.total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              small
            />
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, nextTick } from "vue";
import { Search, Refresh, Download, ArrowDown } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import axios from "axios";
import * as echarts from "echarts";
import * as XLSX from "xlsx";
import _ from "lodash";

// 视图高度
const view = reactive({
  height: window.innerHeight,
});

window.onresize = function () {
  view.height = window.innerHeight;
  if (myChart) {
    myChart.resize();
  }
};

// 图表实例
let myChart: echarts.ECharts | null = null;

// 加载状态
const loading = ref(false);
const stationLoading = ref(false);
const dataTypeLoading = ref(false);
const exportLoading = ref(false);
const hasData = ref(false);

// 查询表单
const searchForm = reactive({
  stationTypeCode: "",
  stationCode: "",
  dataTypes: [] as string[], // 改为数组支持多选
});

// 日期范围
const dateRange = ref<[string, string] | null>(null);

// 图表标题
const chartTitle = ref("");

// 选项数据
const stationTypeOptions = ref<any[]>([]);
const stationOptions = ref<any[]>([]);
const dataTypeOptions = ref<any[]>([]);
const filteredDataTypeOptions = ref<any[]>([]);

// 表格数据
const tableData = ref<any[]>([]);

// 分页参数
const pagination = reactive({
  pageNum: 1,
  pageSize: 20,
  total: 0,
});

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近7天',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: '最近30天',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    },
  },
  {
    text: '最近3个月',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    },
  },
];

// 数据类型分组 - 只有在数据类型较多时使用
const groupedDataTypes = computed(() => {
  if (!dataTypeOptions.value.length) return [];
  
  // 简单的分组逻辑，可根据实际业务调整
  const groups = _.groupBy(dataTypeOptions.value, (item) => {
    const name = item.dataTypeName || item.dataTypeCode || '';
    // 根据名称关键词分组
    if (name.includes('水位') || name.includes('水深')) return '水位监测';
    if (name.includes('流量') || name.includes('流速')) return '流量监测';
    if (name.includes('降雨') || name.includes('降水') || name.includes('雨量')) return '降雨监测';
    if (name.includes('温度') || name.includes('气温')) return '温度监测';
    if (name.includes('湿度')) return '湿度监测';
    if (name.includes('风') || name.includes('风速') || name.includes('风向')) return '风况监测';
    if (name.includes('压力') || name.includes('气压')) return '压力监测';
    if (name.includes('PH') || name.includes('ph') || name.includes('酸碱')) return '水质监测';
    return '其他监测';
  });
  
  return Object.keys(groups).map(key => ({
    label: key,
    options: groups[key]
  }));
});

// 是否可以查询 - 修改验证条件
const isSearchValid = computed(() => {
  return (
    searchForm.stationTypeCode &&
    searchForm.stationCode &&
    searchForm.dataTypes.length > 0 && // 至少选择一个数据类型
    dateRange.value &&
    dateRange.value.length === 2
  );
});

// 数据类型过滤方法
const filterDataType = (query: string) => {
  if (query !== '') {
    filteredDataTypeOptions.value = dataTypeOptions.value.filter(item => {
      const name = item.dataTypeName || item.dataTypeCode || '';
      const code = item.dataTypeCode || '';
      return name.toLowerCase().includes(query.toLowerCase()) || 
             code.toLowerCase().includes(query.toLowerCase());
    });
  } else {
    filteredDataTypeOptions.value = dataTypeOptions.value;
  }
};

// 导出功能相关方法
const exportChart = async () => {
  if (!myChart || !hasData.value) {
    ElMessage.warning("暂无图表数据可导出");
    return;
  }

  try {
    exportLoading.value = true;
    
    // 获取图表的base64数据
    const imageData = myChart.getDataURL({
      type: 'png',
      pixelRatio: 2,
      backgroundColor: '#fff'
    });

    // 创建下载链接
    const link = document.createElement('a');
    link.href = imageData;
    link.download = `${chartTitle.value || '测站数据图表'}_${new Date().toLocaleDateString()}.png`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    ElMessage.success("图表导出成功");
  } catch (error) {
    console.error("导出图表失败:", error);
    ElMessage.error("导出图表失败");
  } finally {
    exportLoading.value = false;
  }
};

const handleExportData = async (command: string) => {
  if (!hasData.value || tableData.value.length === 0) {
    ElMessage.warning("暂无数据可导出");
    return;
  }

  try {
    exportLoading.value = true;

    // 首先获取所有数据（不分页）
    const allData = await getAllData();
    
    if (command === 'excel') {
      await exportToExcel(allData);
    } else if (command === 'csv') {
      await exportToCSV(allData);
    }

    ElMessage.success(`数据导出成功`);
  } catch (error) {
    console.error("导出数据失败:", error);
    ElMessage.error("导出数据失败");
  } finally {
    exportLoading.value = false;
  }
};

// 获取所有数据（不分页）
const getAllData = async () => {
  try {
    const params = {
      stationCode: searchForm.stationCode,
      stationTypeCode: searchForm.stationTypeCode,
      dataTypes: searchForm.dataTypes.join(','),
      startDate: dateRange.value ? dateRange.value[0] + " 00:00:00" : undefined,
      endDate: dateRange.value ? dateRange.value[1] + " 23:59:59" : undefined,
      pageNum: 1,
      pageSize: 10000, // 获取足够多的数据
    };

    const response = await axios.get(
      "/algorithmApi/stationApi/monitoring-data",
      { params }
    );

    if (response.data.code === 200) {
      return response.data.data?.list || [];
    } else {
      throw new Error(response.data.message || "获取数据失败");
    }
  } catch (error) {
    throw error;
  }
};

// 导出为Excel
const exportToExcel = async (data: any[]) => {
  const exportData = data.map(item => ({
    '测站编码': item.stationCode,
    '测站名称': item.stationName,
    '测站类型编码': item.stationTypeCode,
    '测站类型名称': item.stationTypeName,
    '数据类型编码': item.dataType,
    '数据类型名称': item.dataTypeName,
    '监测时间': formatDate(item.monitoringDate),
    '监测值': formatValue(item.monitoringValue)
  }));

  const worksheet = XLSX.utils.json_to_sheet(exportData);
  const workbook = XLSX.utils.book_new();
  
  // 设置列宽
  const colWidths = [
    { wch: 15 }, // 测站编码
    { wch: 20 }, // 测站名称
    { wch: 15 }, // 测站类型编码
    { wch: 20 }, // 测站类型名称
    { wch: 15 }, // 数据类型编码
    { wch: 20 }, // 数据类型名称
    { wch: 20 }, // 监测时间
    { wch: 15 }  // 监测值
  ];
  worksheet['!cols'] = colWidths;

  XLSX.utils.book_append_sheet(workbook, worksheet, "监测数据");
  
  const fileName = `${chartTitle.value || '测站监测数据'}_${new Date().toLocaleDateString()}.xlsx`;
  XLSX.writeFile(workbook, fileName);
};

// 导出为CSV
const exportToCSV = async (data: any[]) => {
  const exportData = data.map(item => ({
    '测站编码': item.stationCode,
    '测站名称': item.stationName,
    '测站类型编码': item.stationTypeCode,
    '测站类型名称': item.stationTypeName,
    '数据类型编码': item.dataType,
    '数据类型名称': item.dataTypeName,
    '监测时间': formatDate(item.monitoringDate),
    '监测值': formatValue(item.monitoringValue)
  }));

  const worksheet = XLSX.utils.json_to_sheet(exportData);
  const csv = XLSX.utils.sheet_to_csv(worksheet);
  
  // 添加BOM以支持中文
  const BOM = '\uFEFF';
  const blob = new Blob([BOM + csv], { type: 'text/csv;charset=utf-8;' });
  
  const link = document.createElement('a');
  link.href = URL.createObjectURL(blob);
  link.download = `${chartTitle.value || '测站监测数据'}_${new Date().toLocaleDateString()}.csv`;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  URL.revokeObjectURL(link.href);
};

// 生命周期钩子
onMounted(async () => {
  initChart();

  // 设置默认日期范围 (最近30天)
  const end = new Date();
  const start = new Date();
  start.setDate(start.getDate() - 30);

  dateRange.value = [formatDateToString(start), formatDateToString(end)];

  await loadStationTypesWithDefault();
});

// 加载测站类型选项并默认选择第一个
const loadStationTypesWithDefault = async () => {
  try {
    loading.value = true;
    const response = await axios.get("/algorithmApi/api1/station-type1/list");
    if (response.data.code === 200) {
      stationTypeOptions.value = response.data.data || [];

      if (stationTypeOptions.value.length > 0) {
        searchForm.stationTypeCode =
          stationTypeOptions.value[0].stationTypeCode;
        await Promise.all([
          loadDataTypesWithDefault(searchForm.stationTypeCode),
          loadStationsWithDefault(searchForm.stationTypeCode),
        ]);
      }
    } else {
      ElMessage.error("获取测站类型失败");
    }
  } catch (error) {
    console.error("加载测站类型错误:", error);
    ElMessage.error("获取测站类型失败");
  } finally {
    loading.value = false;
  }
};

// 加载测站选项并默认选择第一个
const loadStationsWithDefault = async (stationTypeCode: string) => {
  try {
    stationLoading.value = true;
    const response = await axios.get("/algorithmApi/stationApi/station-info", {
      params: { stationTypeCode, pageSize: 1000 },
    });
    if (response.data.code === 200) {
      stationOptions.value = response.data.data?.list || [];

      if (stationOptions.value.length > 0) {
        searchForm.stationCode = stationOptions.value[0].stcd;
        await autoSearchIfReady();
      }
    } else {
      ElMessage.error("获取测站信息失败");
    }
  } catch (error) {
    console.error("加载测站信息错误:", error);
    ElMessage.error("获取测站信息失败");
  } finally {
    stationLoading.value = false;
  }
};

// 从测站数据要素管理模块加载数据类型 - 默认选择前3个
const loadDataTypesWithDefault = async (stationTypeCode: string) => {
  try {
    dataTypeLoading.value = true;
    const response = await axios.get("/algorithmApi/stationApi/station-type", {
      params: {
        stationTypeCode: stationTypeCode,
        pageSize: 1000,
      },
    });

    if (response.data.code === 200) {
      const stationTypes = response.data.data?.list || [];

      const typeMap = new Map();
      stationTypes.forEach((item: any) => {
        if (item.dataTypeCode && !typeMap.has(item.dataTypeCode)) {
          typeMap.set(item.dataTypeCode, {
            dataTypeCode: item.dataTypeCode,
            dataTypeName: item.dataTypeName || item.dataTypeCode,
          });
        }
      });

      dataTypeOptions.value = Array.from(typeMap.values());
      filteredDataTypeOptions.value = dataTypeOptions.value;

      // 默认选择前3个数据类型（如果有的话）
      if (dataTypeOptions.value.length > 0) {
        const defaultTypes = dataTypeOptions.value.slice(0, Math.min(3, dataTypeOptions.value.length));
        searchForm.dataTypes = defaultTypes.map(item => item.dataTypeCode);
        await autoSearchIfReady();
      }
    } else {
      ElMessage.error("获取数据类型失败");
    }
  } catch (error) {
    console.error("加载数据类型错误:", error);
    ElMessage.error("获取数据类型失败");
  } finally {
    dataTypeLoading.value = false;
  }
};

// 自动执行查询
const autoSearchIfReady = async () => {
  if (isSearchValid.value) {
    await loadMonitoringData();
  }
};

// 加载测站选项
const loadStations = async (stationTypeCode: string) => {
  try {
    stationLoading.value = true;
    const response = await axios.get("/algorithmApi/stationApi/station-info", {
      params: { stationTypeCode, pageSize: 1000 },
    });
    if (response.data.code === 200) {
      stationOptions.value = response.data.data?.list || [];
    } else {
      ElMessage.error("获取测站信息失败");
    }
  } catch (error) {
    console.error("加载测站信息错误:", error);
    ElMessage.error("获取测站信息失败");
  } finally {
    stationLoading.value = false;
  }
};

// 从测站数据要素管理模块加载数据类型
const loadDataTypes = async (stationTypeCode: string) => {
  try {
    dataTypeLoading.value = true;
    const response = await axios.get("/algorithmApi/stationApi/station-type", {
      params: {
        stationTypeCode: stationTypeCode,
        pageSize: 1000,
      },
    });

    if (response.data.code === 200) {
      const stationTypes = response.data.data?.list || [];

      const typeMap = new Map();
      stationTypes.forEach((item: any) => {
        if (item.dataTypeCode && !typeMap.has(item.dataTypeCode)) {
          typeMap.set(item.dataTypeCode, {
            dataTypeCode: item.dataTypeCode,
            dataTypeName: item.dataTypeName || item.dataTypeCode,
          });
        }
      });

      dataTypeOptions.value = Array.from(typeMap.values());
      filteredDataTypeOptions.value = dataTypeOptions.value;
    } else {
      ElMessage.error("获取数据类型失败");
    }
  } catch (error) {
    console.error("加载数据类型错误:", error);
    ElMessage.error("获取数据类型失败");
  } finally {
    dataTypeLoading.value = false;
  }
};

// 加载监测数据 - 支持多个数据类型
const loadMonitoringData = async () => {
  if (!isSearchValid.value) {
    ElMessage.warning("请完善查询条件");
    return;
  }

  try {
    loading.value = true;
    hasData.value = false;

    // 构建查询参数 - 支持多个数据类型
    const params = {
      stationCode: searchForm.stationCode,
      stationTypeCode: searchForm.stationTypeCode,
      dataTypes: searchForm.dataTypes.join(','), // 将数组转为逗号分隔的字符串
      startDate: dateRange.value ? dateRange.value[0] + " 00:00:00" : undefined,
      endDate: dateRange.value ? dateRange.value[1] + " 23:59:59" : undefined,
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize,
    };

    const response = await axios.get(
      "/algorithmApi/stationApi/monitoring-data",
      { params }
    );

    if (response.data.code === 200) {
      const responseData = response.data.data;
      tableData.value = responseData.list || [];
      pagination.total = responseData.total || 0;

      hasData.value = tableData.value.length > 0;

      if (hasData.value) {
        updateChart();
        updateChartTitle();
      } else {
        chartTitle.value = "";
      }
    } else {
      ElMessage.error(response.data.message || "查询失败");
    }
  } catch (error) {
    console.error("加载监测数据错误:", error);
    ElMessage.error("查询失败");
  } finally {
    loading.value = false;
  }
};

// 更新图表标题
const updateChartTitle = () => {
  const stationType = stationTypeOptions.value.find(
    (t) => t.stationTypeCode === searchForm.stationTypeCode
  );
  const station = stationOptions.value.find(
    (s) => s.stcd === searchForm.stationCode
  );
  
  const selectedDataTypes = dataTypeOptions.value.filter(
    (d) => searchForm.dataTypes.includes(d.dataTypeCode)
  );
  
  const dataTypeNames = selectedDataTypes.map(d => d.dataTypeName || d.dataTypeCode).join('、');

  chartTitle.value = `${stationType?.stationTypeName || ""} - ${
    station?.stnm || station?.stcd || ""
  } - ${dataTypeNames} 监测数据`;
};

// 初始化图表
const initChart = () => {
  nextTick(() => {
    const chartDom = document.getElementById("lineChart");
    if (chartDom) {
      myChart = echarts.init(chartDom);

      const option = {
        tooltip: {
          trigger: "axis",
          formatter: function (params: any) {
            let result = params[0].name + '<br/>';
            params.forEach((param: any) => {
              result += `${param.marker}${param.seriesName}: ${param.value}<br/>`;
            });
            return result;
          },
        },
        legend: {
          data: [],
          top: '10px'
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          top: "60px",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: [],
        },
        yAxis: {
          type: "value",
          axisLabel: {
            formatter: "{value}",
          },
        },
        series: [],
      };

      myChart.setOption(option);
    }
  });
};

// 更新图表数据 - 支持多个数据系列
const updateChart = () => {
  if (!myChart) return;

  // 按数据类型分组数据
  const groupedData = _.groupBy(tableData.value, 'dataType');
  
  // 获取所有时间点并排序
  const allDates = _.uniq(
    tableData.value.map(item => formatDate(item.monitoringDate))
  ).sort((a, b) => new Date(a).getTime() - new Date(b).getTime());

  // 生成颜色数组
  const colors = [
    '#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399',
    '#FF7F50', '#87CEEB', '#DA70D6', '#32CD32', '#FF6347'
  ];

  // 构建系列数据
  const series: any[] = [];
  const legendData: string[] = [];
  
  Object.keys(groupedData).forEach((dataTypeCode, index) => {
    const dataType = dataTypeOptions.value.find(d => d.dataTypeCode === dataTypeCode);
    const seriesName = dataType?.dataTypeName || dataTypeCode;
    
    // 为每个时间点创建数据，如果没有数据则为null
    const seriesData = allDates.map(date => {
      const dataPoint = groupedData[dataTypeCode].find(
        item => formatDate(item.monitoringDate) === date
      );
      return dataPoint ? dataPoint.monitoringValue : null;
    });

    legendData.push(seriesName);
    
    series.push({
      name: seriesName,
      type: "line",
      data: seriesData,
      smooth: true,
      symbol: "circle",
      symbolSize: 6,
      itemStyle: {
        color: colors[index % colors.length],
      },
      lineStyle: {
        width: 2,
      },
      connectNulls: false, // 不连接空值点
    });
  });

  myChart.setOption({
    legend: {
      data: legendData,
    },
    xAxis: {
      data: allDates,
    },
    series: series,
  });

  myChart.resize();
};

// 事件处理函数
const handleStationTypeChange = async (value: string) => {
  searchForm.stationCode = "";
  searchForm.dataTypes = []; // 清空数据类型选择
  stationOptions.value = [];
  dataTypeOptions.value = [];
  filteredDataTypeOptions.value = [];

  if (value) {
    await Promise.all([loadStations(value), loadDataTypes(value)]);
  }
};

const handleStationChange = async (value: string) => {
  await autoSearchIfReady();
};

const handleDataTypeChange = async (values: string[]) => {
  await autoSearchIfReady();
};

const handleSearch = () => {
  pagination.pageNum = 1;
  loadMonitoringData();
};

const handleReset = () => {
  searchForm.stationTypeCode = "";
  searchForm.stationCode = "";
  searchForm.dataTypes = []; // 重置为空数组
  stationOptions.value = [];
  dataTypeOptions.value = [];
  filteredDataTypeOptions.value = [];

  const end = new Date();
  const start = new Date();
  start.setDate(start.getDate() - 30);

  dateRange.value = [formatDateToString(start), formatDateToString(end)];

  tableData.value = [];
  hasData.value = false;
  chartTitle.value = "";

  if (myChart) {
    myChart.setOption({
      legend: { data: [] },
      xAxis: { data: [] },
      series: [],
    });
  }
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  loadMonitoringData();
};

const handleCurrentChange = (page: number) => {
  pagination.pageNum = page;
  loadMonitoringData();
};

// 工具函数
const formatDate = (date: string | Date) => {
  if (!date) return "-";
  const d = new Date(date);
  return `${d.getFullYear()}-${(d.getMonth() + 1)
    .toString()
    .padStart(2, "0")}-${d.getDate().toString().padStart(2, "0")} ${d
    .getHours()
    .toString()
    .padStart(2, "0")}:${d.getMinutes().toString().padStart(2, "0")}`;
};

const formatDateToString = (date: Date) => {
  return `${date.getFullYear()}-${(date.getMonth() + 1)
    .toString()
    .padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")}`;
};

const formatValue = (value: any) => {
  if (value === null || value === undefined) return "-";
  return Number(value).toFixed(4);
};
</script>

<style lang="scss" scoped>
.station-data-chart {
  padding: 16px;
  overflow: hidden;

  .layout-container {
    display: flex;
    gap: 16px;
    overflow: hidden;

    .left-panel {
      width: 320px;
      min-width: 320px;
      overflow: hidden;

      .search-card {
        display: flex;
        flex-direction: column;

        .card-header {
          font-weight: 600;
          color: #303133;
        }

        .form-container {
          flex: 1;
          overflow-y: auto;
          padding-right: 8px;

          &::-webkit-scrollbar {
            width: 6px;
          }

          &::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 3px;
          }

          &::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 3px;

            &:hover {
              background: #a8a8a8;
            }
          }
        }

        .el-radio {
          display: flex;
          align-items: center;

          :deep(.el-radio__label) {
            padding-left: 8px;
            line-height: 1.4;
          }
        }

        .el-form-item {
          margin-bottom: 20px;

          :deep(.el-form-item__label) {
            font-weight: 600;
            color: #606266;
          }
        }

        .selected-types-info {
          margin-top: 8px;
          font-size: 12px;
          color: #409EFF;
          text-align: center;
        }
      }
    }

    .right-panel {
      flex: 1;
      display: flex;
      flex-direction: column;
      gap: 16px;
      min-width: 0;
      overflow: hidden;

      .chart-card {
        display: flex;
        flex-direction: column;
        overflow: hidden;

        .chart-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 16px;

          .chart-title {
            flex: 1;

            h3 {
              margin: 0;
              font-weight: 600;
              color: #303133;
            }
          }

          .chart-actions {
            flex-shrink: 0;
          }
        }

        .chart-container {
          flex: 1;
          width: 100%;
          min-height: 200px;
        }
      }

      .table-card {
        display: flex;
        flex-direction: column;
        overflow: hidden;

        .table-header {
          display: flex;
          justify-content: space-between;
          align-items: center;

          .table-info {
            display: flex;
            align-items: center;
            gap: 12px;

            .title {
              font-weight: 600;
              color: #303133;
            }

            .data-count {
              font-size: 12px;
              color: #909399;
            }
          }

          .table-actions {
            flex-shrink: 0;
          }
        }

        .table-container {
          flex: 1;
          overflow: hidden;
        }

        .pagination-container {
          margin-top: 16px;
          display: flex;
          justify-content: flex-end;
          padding: 0 16px 16px 16px;
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .station-data-chart {
    .layout-container {
      flex-direction: column;

      .left-panel {
        width: 100%;
        min-width: auto;
        height: auto !important;

        .search-card {
          height: auto !important;
        }

        .form-container {
          height: auto !important;
          max-height: 400px;
        }
      }

      .right-panel {
        .chart-card {
          height: 400px !important;

          .chart-container {
            height: 300px !important;
          }
        }

        .table-card {
          height: 400px !important;

          .table-container {
            height: 300px !important;
          }
        }
      }
    }
  }
}
</style>